package cn.iocoder.yudao.module.promotion.controller.admin.shortlinkdetail;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.promotion.controller.admin.shortlinkdetail.vo.*;
import cn.iocoder.yudao.module.promotion.controller.admin.shortlinklog.vo.ShortLinkLogCreateReqVO;
import cn.iocoder.yudao.module.promotion.controller.admin.shortlinklog.vo.ShortLinkLogExportReqVO;
import cn.iocoder.yudao.module.promotion.convert.shortlinkdetail.ShortLinkDetailConvert;
import cn.iocoder.yudao.module.promotion.dal.dataobject.shortlinkdetail.ShortLinkDetailDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.shortlinkgeneratee.ShortLinkGenerateeDO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.shortlinklog.ShortLinkLogDO;
import cn.iocoder.yudao.module.promotion.service.shortlinkdetail.ShortLinkDetailService;
import cn.iocoder.yudao.module.promotion.service.shortlinkgeneratee.ShortLinkGenerateeService;
import cn.iocoder.yudao.module.promotion.service.shortlinklog.ShortLinkLogService;
import io.swagger.v3.oas.annotations.Parameters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.annotation.security.PermitAll;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.pojo.PageParam.PAGE_SIZE_NONE;
import static cn.iocoder.yudao.module.promotion.util.PromotionUtils.getDeviceType;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 短链接列")
@RestController
@RequestMapping("/promotion/short-link-detail")
@Validated
@Slf4j
public class ShortLinkDetailController {

    @Resource
    private ShortLinkDetailService shortLinkDetailService;

    @Resource
    private ShortLinkGenerateeService shortLinkGenerateeService;

    @Resource
    private ShortLinkLogService shortLinkLogService;

    @PostMapping("/create")
    @Operation(summary = "创建短链接列")
    @PreAuthorize("@ss.hasPermission('zfkj:short-link-detail:create')")
    public CommonResult<Long> createShortLinkDetail(@Valid @RequestBody ShortLinkDetailCreateReqVO createReqVO) {
        return success(shortLinkDetailService.createShortLinkDetail(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新短链接列")
    @PreAuthorize("@ss.hasPermission('zfkj:short-link-detail:update')")
    public CommonResult<Boolean> updateShortLinkDetail(@Valid @RequestBody ShortLinkDetailUpdateReqVO updateReqVO) {
        shortLinkDetailService.updateShortLinkDetail(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除短链接列")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('zfkj:short-link-detail:delete')")
    public CommonResult<Boolean> deleteShortLinkDetail(@RequestParam("id") Long id) {
        shortLinkDetailService.deleteShortLinkDetail(id);
        return success(true);
    }

    @DeleteMapping("/deleteList")
    @Operation(summary = "删除短链接列表")
    @Parameter(name = "shortLinkId", description = "编号", required = true)
    public CommonResult<Boolean> deleteShortLinkDetailList(@RequestParam("shortLinkId") Long shortLinkId) {
        shortLinkDetailService.deleteShortLinkDetailList(shortLinkId);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得短链接列")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('zfkj:short-link-detail:query')")
    public CommonResult<ShortLinkDetailRespVO> getShortLinkDetail(@RequestParam("id") Long id) {
        ShortLinkDetailDO shortLinkDetail = shortLinkDetailService.getShortLinkDetail(id);
        return success(ShortLinkDetailConvert.INSTANCE.convert(shortLinkDetail));
    }

    @GetMapping("/list")
    @Operation(summary = "获得短链接列列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('zfkj:short-link-detail:query')")
    public CommonResult<List<ShortLinkDetailRespVO>> getShortLinkDetailList(@RequestParam("ids") Collection<Long> ids) {
        List<ShortLinkDetailDO> list = shortLinkDetailService.getShortLinkDetailList(ids);
        return success(ShortLinkDetailConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得短链接列分页")
    @PreAuthorize("@ss.hasPermission('zfkj:short-link-detail:query')")
    public CommonResult<PageResult<ShortLinkDetailRespVO>> getShortLinkDetailPage(@Valid ShortLinkDetailPageReqVO pageVO) {
        PageResult<ShortLinkDetailDO> pageResult = shortLinkDetailService.getShortLinkDetailPage(pageVO);
        return success(ShortLinkDetailConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出短链接列 Excel")
    @PreAuthorize("@ss.hasPermission('zfkj:short-link-detail:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportShortLinkDetailExcel(@Valid ShortLinkDetailExportReqVO exportReqVO,
                                           HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PAGE_SIZE_NONE);
        List<ShortLinkDetailDO> list = shortLinkDetailService.getShortLinkDetailList(exportReqVO);
        // 导出 Excel
        List<ShortLinkDetailExcelVO> datas = ShortLinkDetailConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "短链接列.xls", "数据", ShortLinkDetailExcelVO.class, datas);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入用户模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<ShortLinkDetaiTemplExcelVO> list = Arrays.asList(
                ShortLinkDetaiTemplExcelVO.builder().phoneNumber(Long.valueOf("18912341234")).build());
        // 输出
        ExcelUtils.write(response, "短链接导入模板.xls", "短链接列表", ShortLinkDetaiTemplExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "批量导入短链接")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "shortLinkId", description = "shortLinkId", required = true),
            @Parameter(name = "name", description = "name", required = true),
            @Parameter(name = "shortLinkDomain", description = "shortLinkDomain", required = true)
    })
    @PreAuthorize("@ss.hasPermission('trade:order:update')")
    public CommonResult<ShortLinkDetailImportResponseVO> importExcel(@RequestParam("file") MultipartFile file, @RequestParam("shortLinkId") Long shortLinkId, @RequestParam("name") String name, @RequestParam("shortLinkDomain") String shortLinkDomain) throws Exception {
        List<ShortLinkDetailImportExcelVO> list = ExcelUtils.read(file, ShortLinkDetailImportExcelVO.class);
        return success(shortLinkDetailService.deliveryShortLink(list, shortLinkId, name, shortLinkDomain));
    }

    @GetMapping("/{shortUrl}")
    @Operation(summary = "短链接访问")
    @PermitAll
    public void redirectUrl(@RequestHeader("Host") String host, @PathVariable String shortUrl, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("shortUrl:{}, host:{}", shortUrl, host);
        ShortLinkDetailPageReqVO detailVO = new ShortLinkDetailPageReqVO();
        detailVO.setShortUrl(host + "/" + shortUrl);
        //detailVO.setShortUrl("http://localhost:48090/admin-api/promotion/short-link-detail/" + shortUrl);
        ShortLinkDetailDO longUrl = shortLinkDetailService.getLongUrl(detailVO);
        if (longUrl != null) {
            ShortLinkGenerateeDO shortLinkGeneratee = shortLinkGenerateeService.getShortLinkGeneratee(longUrl.getShortLinkId());
            if (shortLinkGeneratee != null) {
                //记录访问日志
                String equipment = getDeviceType(request);
                if(!equipment.equals("Unknown")){
                    ShortLinkLogExportReqVO exportReqVO = new ShortLinkLogExportReqVO();
                    exportReqVO.setShortLinkId(longUrl.getShortLinkId());
                    exportReqVO.setPhoneNumber(longUrl.getPhoneNumber());
                    exportReqVO.setShortLinkDetailId(longUrl.getId());
                    exportReqVO.setIp(ServletUtils.getClientIP(request));
                    List<ShortLinkLogDO> shortLinkLogList = shortLinkLogService.getShortLinkLogList(exportReqVO);
                    //同一个手机号ip访问同一个url只记录一次
                    if(shortLinkLogList.size() == 0){
                        ShortLinkLogCreateReqVO shortLinkLogCreateReqVO = new ShortLinkLogCreateReqVO();
                        shortLinkLogCreateReqVO.setShortLinkId(longUrl.getShortLinkId());
                        shortLinkLogCreateReqVO.setShortLinkDetailId(longUrl.getId());
                        shortLinkLogCreateReqVO.setShortLinkName(longUrl.getName());
                        shortLinkLogCreateReqVO.setShortUrl(longUrl.getShortUrl());
                        shortLinkLogCreateReqVO.setGenerateeName(shortLinkGeneratee.getName());
                        shortLinkLogCreateReqVO.setBatchNumber(longUrl.getBatchNumber());
                        shortLinkLogCreateReqVO.setPhoneNumber(longUrl.getPhoneNumber());
                        shortLinkLogCreateReqVO.setIp(ServletUtils.getClientIP(request));
                        shortLinkLogCreateReqVO.setEquipment(equipment);
                        shortLinkLogCreateReqVO.setStatus((byte) 0);
                        TenantContextHolder.setTenantId(1L);
                        shortLinkLogService.createShortLinkLog(shortLinkLogCreateReqVO);
                    }
                }
                response.sendRedirect(shortLinkGeneratee.getLongUrl());
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}
